<template>
  <div class="app-container">
    <div class="metadata-header">
      <el-row :gutter="10">
        <el-col :span="18">
          <h2>元数据预览 - {{ datasetName }}</h2>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" icon="el-icon-refresh" @click="loadMetadata">
            刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form :model="datasetInfo" label-width="120px" class="metadata-form">

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="数据集ID">
                <el-input v-model="datasetInfo.datasetId" disabled />
              </el-form-item>
              <el-form-item label="数据集名称">
                <el-input v-model="datasetInfo.datasetName" disabled />
              </el-form-item>
              <el-form-item label="数据集编码">
                <el-input v-model="datasetInfo.datasetCode" disabled />
              </el-form-item>
              <el-form-item label="数据集类型">
                <el-input v-model="datasetInfo.datasetType" disabled />
              </el-form-item>
              <el-form-item label="数据源">
                <el-input v-model="datasetInfo.datasourceName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本">
                <el-input v-model="datasetInfo.version" disabled />
              </el-form-item>
              <el-form-item label="数据量">
                <el-input v-model="datasetInfo.dataCount" disabled />
              </el-form-item>
              <el-form-item label="状态">
                <el-input v-model="datasetInfo.statusText" disabled />
              </el-form-item>
              <el-form-item label="创建时间">
                <el-input v-model="datasetInfo.createTime" disabled />
              </el-form-item>
              <el-form-item label="更新时间">
                <el-input v-model="datasetInfo.updateTime" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="数据集定义">
                <el-input type="textarea" resize="none" :rows="3" v-model="datasetInfo.datasetDefinition" disabled />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>

      <!-- 字段信息 -->
      <el-tab-pane label="字段信息" name="fields">
        <div class="field-section">
          <el-input v-model="fieldQuery" placeholder="搜索字段名称或描述" clearable @keyup.enter.native="handleFieldSearch"
            class="field-search" />
          <el-table v-loading="fieldLoading" :data="filteredFields" border style="width: 100%">
            <el-table-column prop="name" label="列名" width="180" />
            <el-table-column prop="type" label="数据类型" width="150" />
            <el-table-column prop="displayName" label="显示名称" width="180" />
            <el-table-column prop="fieldComment" label="数据描述" show-overflow-tooltip />
          </el-table>
          <div v-if="!fieldLoading && fields.length === 0" class="empty-data">
            暂无字段信息
          </div>
        </div>
      </el-tab-pane>

      <!-- 统计信息 -->
      <el-tab-pane label="统计信息" name="stats">
        <el-table v-loading="statsLoading" :data="statsList" border style="width: 100%">
          <el-table-column prop="statName" label="统计项" width="180" />
          <el-table-column prop="statValue" label="统计值" />
        </el-table>
        <div v-if="!statsLoading && statsList.length === 0" class="empty-data">
          暂无统计信息
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getDatasetMetadata } from "@/api/system/dataset";

export default {
  name: "DatasetMetadata",
  data() {
    return {
      datasetId: this.$route.params.datasetId,
      datasetName: "",
      datasetInfo: {
        datasetId: "",
        datasetName: "",
        datasetCode: "",
        datasetType: "",
        datasourceName: "",
        version: "",
        dataCount: "",
        statusText: "",
        createTime: "",
        updateTime: ""
      },
      fields: [],
      fieldQuery: "",
      fieldLoading: false,
      statsList: [],
      statsLoading: false,
      activeTab: "basic",
      loading: false
    };
  },
  computed: {
    filteredFields() {
      if (!this.fieldQuery) {
        return this.fields;
      }
      const query = this.fieldQuery.toLowerCase();
      return this.fields.filter(field =>
        field.fieldName.toLowerCase().includes(query) ||
        (field.fieldComment && field.fieldComment.toLowerCase().includes(query))
      );
    }
  },
  created() {
    this.loadMetadata();
  },
  methods: {
    loadMetadata() {
      this.loading = true;
      this.fieldLoading = true;

      // 尝试从后端获取数据
      getDatasetMetadata(this.datasetId)
        .then(response => {
          if (response && response.code === 200 && response.data) {
            this.processDatasetData(response.data);
          } else {
            console.error('后端返回数据格式错误:', response);
            this.$modal.msgWarning('后端数据异常，显示模拟数据');
            this.loadMockData();
          }
        })
        .catch(error => {
          console.error('加载元数据失败:', error);
          this.$modal.msgWarning('后端接口异常，显示模拟数据');
          this.loadMockData();
        })
        .finally(() => {
          this.loading = false;
          this.fieldLoading = false;
          this.statsLoading = false;
        });
    },

    // 处理从后端获取的数据
    processDatasetData(data) {
      // 设置基本信息
      this.datasetName = data.datasetName || `数据集${this.datasetId}`;
      this.datasetInfo = {
        datasetId: data.datasetId || this.datasetId,
        datasetName: data.datasetName || `数据集${this.datasetId}`,
        datasetCode: data.datasetCode || `DATASET_${this.datasetId}`,
        datasetType: this.getDatasetTypeText(data.datasetType) || '表',
        datasetDefinition: data.datasetDefinition || '无',
        datasourceName: data.datasourceName || '默认数据源',
        version: data.version || '1.0',
        dataCount: data.dataCount || '0',
        statusText: data.status === '0' ? '启用' : (data.status === '1' ? '停用' : '未知'),
        createTime: data.createTime || new Date().toLocaleString(),
        updateTime: data.updateTime || new Date().toLocaleString()
      };

      // 从metadata字段获取字段信息
      this.fields = [];
      if (data.metadata) {
        try {
          // 解析metadata字段（假设是JSON字符串）
          console.debug('原始metadata:', data.metadata);
          const metadata = typeof data.metadata === 'string' ? JSON.parse(data.metadata) : data.metadata;
          this.fields = metadata.fields;

        } catch (error) {
          console.error('解析metadata失败:', error);
        }
      } else {
        console.error('解析metadata失败: metadata字段为空');
      }

      // 设置统计信息
      this.statsList = [
        { statName: '总字段数', statValue: this.fields.length },
        { statName: '主键字段数', statValue: this.fields.filter(f => f.isPrimaryKey).length },
        { statName: '数据量', statValue: data.dataCount || '0' },
        { statName: '版本', statValue: data.version || '1.0' },
        { statName: '最后更新时间', statValue: data.updateTime || '-' }
      ];
    },



    getDatasetTypeText(type) {
      const typeMap = {
        'table': '表',
        'view': '视图',
        'query': 'SQL查询'
      };
      return typeMap[type] || type;
    },

    handleFieldSearch() {
      // 搜索逻辑已在computed中实现
    }
  }
};
</script>

<style scoped>
.metadata-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.metadata-form {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.field-section {
  padding: 20px;
}

.field-search {
  margin-bottom: 15px;
  width: 300px;
}

.empty-data {
  text-align: center;
  padding: 50px;
  color: #999;
}
</style>
